/**
 * Created by Daguang Li on 12/04/2017.
 */
import constants from '../constants'
import $ from 'jquery'

let methods = {
    isEmptyOrNull: (obj) => {
        /// <summary>
        /// Retrieve true when object is empty, undefined or null.
        /// </summary>
        /// <param name='obj'>Object to be checked</param>
        /// <returns type='boolean'>True when object is empty, undefined or null.</returns>
        /// <doc>myPerformance.factory:methods#isEmptyOrNull</doc>
        return ((obj === undefined) ||
            (obj === null) ||
            (typeof obj === 'string' && (obj === '')) ||
            (Array.isArray(obj) && (obj.length === 0)) // Arrays
        );
    },
    urlFormat: function () {
        /// <summary>
        /// Format url using string.format way to match parameters.
        /// </summary>
        /// <returns type='string'>String parsed.</returns>
        /// <doc>myPerformance.factory:methods#urlFormat</doc>
        let args = arguments, url = '', baseUrl = '', qs = '', qsFormatted = '', splitted, vars = [], hash, i;
        if (methods.isEmptyOrNull(args)) {
            return '';
        }
        if (args.length === 1) {
            url = args[0];
        }
        else {
            url = args[0].replace(/\{(\d+)\}/g, (match, number) => {
                return args[parseInt(number, 10) + 1] !== undefined ? encodeURIComponent(args[parseInt(number, 10) + 1]) : '';
            });
        }
        // Remove empty qs parameters
        if (url.indexOf('?') >= 0) {
            splitted = url.split('?');
            baseUrl = splitted[0];
            if (splitted.length > 1) {
                qs = splitted[1].split('&');
                for (i = 0; i < qs.length; i++) {
                    if (qs[i].indexOf('=') >= 0) {
                        hash = qs[i].split('=');
                        vars.push({ code: hash[0], value: hash[1] });
                    }
                    else {
                        vars.push({ code: qs[i], value: '' });
                    }
                }
                // Fill qsFormatted using vars and removing empty values
                for (i = 0; i < vars.length; i++) {
                    if (vars[i].value && vars[i].value !== '') {
                        qsFormatted = qsFormatted + ((qsFormatted === '') ? '?' : '&') + vars[i].code + '=' + vars[i].value;
                    }
                }
            }
        }
        else {
            baseUrl = url;
        }
        return baseUrl + qsFormatted;
    },
    random: () => {
        let nowTime = methods.dateFormat(new Date(), 'MMddhhmmss');

        return nowTime.toString() + Math.floor(Math.random()*100);
    },
    dateFormat: (date, format) => {
        let o = {
            'M+': date.getMonth() + 1,                 //月份
            'd+': date.getDate(),                    //日
            'h+': date.getHours(),                   //小时
            'm+': date.getMinutes(),                 //分
            's+': date.getSeconds(),                 //秒
            'q+': Math.floor((date.getMonth() + 3) / 3), //季度
            'S': date.getMilliseconds()             //毫秒
        };
        if (/(y+)/.test(format))
            format = format.replace(RegExp.$1, (date.getFullYear() + '').substr(4 - RegExp.$1.length));
        for (let k in o)
            if (new RegExp('(' + k + ')').test(format))
                format = format.replace(RegExp.$1, (RegExp.$1.length === 1) ? (o[k]) : (('00' + o[k]).substr(('' + o[k]).length)));
        return format;
    },
    /**
     * 本地数据存储
     *
     * @param {any} key
     * @param {any} value
     * @returns
     */
    setLocalStorage: (key, value) => {
        return localStorage.setItem(key, value);
    },
    /**
     * 本地数据读取
     *
     * @param {any} key
     * @returns
     */
    getLocalStorage: (key) => {
        return localStorage.getItem(key) && localStorage.getItem(key) !== 'null' ? localStorage.getItem(key) : null;
    },
    /**
     * 删除本地数据
     *
     * @param {any} key
     * @returns
     */
    removeLocalStorage: (key) => {
        if(arguments.length === 1) {
            return localStorage.removeItem(key);
        } else {
            return localStorage.clear();
        }
    },
    /**
     * 本地数据存储
     *
     * @param {any} key
     * @param {any} value
     * @returns
     */
    setSessionStorage: (key, value) => {
        return sessionStorage.setItem(key, value);
    },
    /**
     * 本地数据读取
     *
     * @param {any} key
     * @returns
     */
    getSessionStorage: (key) => {
        return sessionStorage.getItem(key) && sessionStorage.getItem(key) !== 'null' ? sessionStorage.getItem(key) : null;
    },
    /**
     * 删除本地数据
     *
     * @param {any} key
     * @returns
     */
    removeSessionStorage: (key) => {
        if(arguments.length === 1) {
            return sessionStorage.removeItem(key);
        } else {
            return sessionStorage.clear();
        }
    },
    parseUrl: () => {
        let url = window.location.href;
        let i = url.indexOf('?');
        if (i === -1) return;
        let querystr = url.substr(i + 1);
        let arr1 = querystr.split('&');
        let arr2 = {};
        for  (i in arr1){
            let ta = arr1[i].split('=');
            arr2[ta[0]] = ta[1];
        }
        return arr2;
    },
    preventScroll: () => {
        // setTimeout(function () {
        //     document.body.addEventListener('touchmove', function(evt) {
        //         // 在需要滚动的div添加scroll类
        //         let scrollE = document.querySelector('.scroll');
        //         if (scrollE && scrollE.contains(evt.target)) {
        //             // do nothing
        //         } else {
        //             evt.preventDefault();
        //         }
        //     });
        // });
        setTimeout(() => {
            var lastY;//最后一次y坐标点
            $(document.body).on('touchstart', function(event) {
                lastY = event.originalEvent.changedTouches[0].clientY;//点击屏幕时记录最后一次Y度坐标。
            });
            $(document.body).on('touchmove', function(event) {
                var y = event.originalEvent.changedTouches[0].clientY;
                var st = $(this).scrollTop(); //滚动条高度
                if (y >= lastY && st <= 10) {//如果滚动条高度小于0，可以理解为到顶了，且是下拉情况下，阻止touchmove事件。
                    lastY = y;
                    event.preventDefault();
                }
                lastY = y;

            });
        });
    },
    getNowData: () => {
        return methods.dateFormat(new Date(), 'yyyy-MM-dd hh:mm:ss');
    },
    getDefaultLanguage: () => {
        let langKey = methods.getLocalStorage(constants.localKey.langKey);
        if (langKey) {
            return langKey;
        } else {
            if (navigator.language.indexOf("en") !== -1) {
                langKey = 'en';
            } else if (navigator.language.indexOf("zh") !== -1) {
                langKey = 'zh';
            } else {
                langKey = 'zh';
            }

            return langKey;
        }
    },
    checkPM25Level: (val) => {
        let retOpt = {};

        if (!val) {
            return retOpt;
        }

        if (val > -1 && val < 36) {
            retOpt.className = 'green';
            retOpt.message = "优";
        }
        else if (val > 35 && val < 76) {
            retOpt.className = 'yellow';
            retOpt.message = "良";
        }
        else if (val > 75 && val < 116) {
            retOpt.className = 'orange';
            retOpt.message = "轻度污染";
        }
        else if (val > 115 && val < 151) {
            retOpt.className = 'red';
            retOpt.message = "中度污染";
        }
        else if (val > 150 && val < 251) {
            retOpt.className = 'violet';
            retOpt.message = "重度污染";
        }
        else if (val > 250) {
            retOpt.className = 'maroon';
            retOpt.message = "严重污染";
        }

        return retOpt;
    },
    checkCO2Level: (val) => {
        let retOpt = {};

        if (!val) {
            return retOpt;
        }

        if (val > -1 && val < 801) {
            retOpt.className = 'green';
            retOpt.message = "优";
        }
        else if (val > 800 && val < 1001) {
            retOpt.className = 'yellow';
            retOpt.message = "良";
        }
        else if (val > 1000) {
            retOpt.className = 'orange';
            retOpt.message = "差";
        }

        return retOpt;
    },
    checkTempLevel: (val) => {
        let retOpt = {};

        if (!val) {
            return retOpt;
        }

        // if (val > -1 && val < 19) {
        if (val < 19) {
            retOpt.className = 'blue';
            retOpt.message = "COMMON_TEMP_LEVEL1";
        }
        else if (val > 18 && val < 27) {
            retOpt.className = 'skyblue';
            retOpt.message = "COMMON_TEMP_LEVEL2";
        }
        else if (val > 26) {
            retOpt.className = 'red';
            retOpt.message = "COMMON_TEMP_LEVEL3";
        }

        return retOpt;
    }
};

export default methods;
